package cz.semjob.framework.main;

import java.io.File;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;

import cz.semjob.framework.DocumentAnnotationResults;
import cz.semjob.framework.DocumentAnnotator;
import cz.semjob.output.EnrichmentOutputter;

@ContextConfiguration(locations = { "classpath:/applicationContext.xml" })
public class DocumentAnnotatorMain {

	/** The bean factory. */
	private static BeanFactory beanFactory = new ClassPathXmlApplicationContext(
			"applicationContext.xml");

	private static DocumentAnnotator documentAnnotator = (DocumentAnnotator) beanFactory
			.getBean("documentAnnotator");

	private static EnrichmentOutputter enrichmentOutputter = (EnrichmentOutputter) beanFactory
			.getBean("enrichmentOutputter");

	private static Logger logger = Logger
			.getLogger(DocumentAnnotatorMain.class);

	private static String documentPath = ""; // "/host/diploma/workspace/enrichment-framework/src/test/resources/data/jds/";
	private static String processedPath = ""; // "/host/diploma/workspace/enrichment-framework/src/test/resources/data/processed/";
	private static String outputFilePath = "";
	private static String ontologyPath = "";

	private static String classifiersPath = "../classifiers/"; // "/host/diploma/workspace/enrichment-framework/src/test/resources/data/jds/";

	public static void main(final String[] args) {
		System.out.println("Semjob Ontology Enrichment");
		boolean errorArgs = false;
		try {
			parseArguments(args);
		} catch (IllegalArgumentException e) {
			System.out.println(e.getMessage());
			printUsage();
			errorArgs = true;
		}
		if (!errorArgs) {
			try {
				List<DocumentAnnotationResults> results = documentAnnotator
						.annotateDocuments(documentPath, processedPath,
								classifiersPath + File.separator + "concepts",
								classifiersPath + File.separator + "relations");
				if (results == null || results.size() == 0) {
					System.out
							.println("No documents have been annotated, check the input paths");
					return;
				}
				for (DocumentAnnotationResults documentAnnotationResults : results) {
					logger.debug(documentAnnotationResults);
				}

				String resultTurtle = enrichmentOutputter.createResultOutput(
						results, ontologyPath);
				logger.debug(resultTurtle);
				FileUtils.writeStringToFile(new File(outputFilePath),
						resultTurtle);
			} catch (Exception e) {
				System.out
						.println("Error occured during enrichment, see log for details: "
								+ e.getMessage());
			}
		}
	}

	private static void parseArguments(final String[] args) {
		if (args == null || args.length == 0) {
			printUsage();
			throw new IllegalArgumentException("\nProvide more arguments.");
		}

		// parse args
		if (args.length < 4) {
			printUsage();
			return;
		}

		documentPath = args[0];
		processedPath = args[1];
		outputFilePath = args[2];
		ontologyPath = args[3];

		if (args.length == 5) {
			classifiersPath = args[4];
		}

		// not all args supplied
		if (outputFilePath == null || outputFilePath.equals("")
				|| documentPath == null || documentPath.equals("")
				|| processedPath == null || processedPath.equals("")
				|| ontologyPath == null || ontologyPath.equals("")) {
			printUsage();
			throw new IllegalArgumentException(
					"Provide more arguments (or correct existing ones).");
		}

		// check the files exist

		File documentPathDirectory = new File(documentPath);
		if (!documentPathDirectory.isDirectory()) {
			// System.out.println(xmlConfigurationFile.getAbsolutePath());
			throw new IllegalArgumentException(documentPath
					+ " directory cannot be found.");
		}

		File processedPathDirectory = new File(processedPath);
		if (!processedPathDirectory.isDirectory()) {
			throw new IllegalArgumentException(processedPath
					+ " directory cannot be found.");
		}

		File classifiersDirectory = new File(classifiersPath);
		if (!classifiersDirectory.isDirectory()) {
			throw new IllegalArgumentException(classifiersPath
					+ " directory cannot be found.");
		}
		

		File ontologyFile = new File(ontologyPath);
		if (!ontologyFile.isFile()) {
			throw new IllegalArgumentException(ontologyPath
					+ " directory cannot be found.");
		}

		File outputFile = new File(outputFilePath);
		File outputDirectory = new File(outputFile.getParent());
		if (!outputDirectory.isDirectory()) {
			throw new IllegalArgumentException(outputDirectory.getPath()
					+ " directory cannot be found.");
		}

		logger.debug("Documents path: " + documentPath);
		logger.debug("Processed path: " + processedPath);
		logger.debug("Classifiers path: " + classifiersPath);
		logger.debug("Output path: " + outputFile);

	}

	/**
	 * Print the usage of the application UI in case user inputs incorrect
	 * parameters or inputs -h or --help.
	 */
	public static void printUsage() {
		System.out
				.println("\nUsage of Semjob Ontology Enrichment:\n"
						+ "semjob_enrichment <directory with text documents>" 
						+ " <directory with linguistically processed text documents>"
						+ " <ontology file>"
						+ " <output file> [classifiers directory]");
	}
}
